from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app import db
from app.models.data import PlantingData, CropVariety, EnvironmentData
from datetime import datetime

bp = Blueprint('data', __name__, url_prefix='/data')

# 种植数据路由
@bp.route('/planting')
@login_required
def planting_list():
    page = request.args.get('page', 1, type=int)
    search_crop = request.args.get('search_crop', '')
    search_region = request.args.get('search_region', '')
    date_from = request.args.get('date_from', '')
    date_to = request.args.get('date_to', '')

    query = PlantingData.query.filter_by(user_id=current_user.id)
    
    if search_crop:
        query = query.filter(PlantingData.crop_type.like(f'%{search_crop}%'))
    if search_region:
        query = query.filter(PlantingData.region.like(f'%{search_region}%'))
    if date_from:
        query = query.filter(PlantingData.planting_date >= datetime.strptime(date_from, '%Y-%m-%d'))
    if date_to:
        query = query.filter(PlantingData.planting_date <= datetime.strptime(date_to, '%Y-%m-%d'))

    pagination = query.order_by(PlantingData.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
        
    return render_template('data/planting_list.html', 
                         pagination=pagination,
                         search_crop=search_crop,
                         search_region=search_region,
                         date_from=date_from,
                         date_to=date_to)

@bp.route('/planting/add', methods=['GET', 'POST'])
@login_required
def planting_add():
    if request.method == 'POST':
        try:
            data = PlantingData(
                user_id=current_user.id,
                crop_type=request.form['crop_type'],
                area=float(request.form['area']),
                region=request.form['region'],
                plot_number=request.form['plot_number'],
                planting_date=datetime.strptime(request.form['planting_date'], '%Y-%m-%d')
            )
            db.session.add(data)
            db.session.commit()
            flash('种植数据添加成功', 'success')
            return redirect(url_for('data.planting_list'))
        except Exception as e:
            flash('数据添加失败', 'danger')
    return render_template('data/planting_form.html')

@bp.route('/planting/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def planting_edit(id):
    data = PlantingData.query.filter_by(id=id, user_id=current_user.id).first_or_404()
    
    if request.method == 'POST':
        try:
            data.crop_type = request.form['crop_type']
            data.area = float(request.form['area'])
            data.region = request.form['region']
            data.plot_number = request.form['plot_number']
            data.planting_date = datetime.strptime(request.form['planting_date'], '%Y-%m-%d')
            
            db.session.commit()
            flash('种植数据更新成功', 'success')
            return redirect(url_for('data.planting_list'))
        except Exception as e:
            flash('数据更新失败', 'danger')
            
    return render_template('data/planting_edit.html', data=data)

@bp.route('/planting/<int:id>/delete', methods=['POST'])
@login_required
def planting_delete(id):
    data = PlantingData.query.filter_by(id=id, user_id=current_user.id).first_or_404()
    try:
        db.session.delete(data)
        db.session.commit()
        flash('种植数据删除成功', 'success')
    except Exception as e:
        flash('删除失败', 'danger')
    return redirect(url_for('data.planting_list'))

# 作物品种路由
@bp.route('/crop')
@login_required
def crop_list():
    page = request.args.get('page', 1, type=int)
    search_name = request.args.get('search_name', '')
    search_type = request.args.get('search_type', '')

    query = CropVariety.query
    
    if search_name:
        query = query.filter(CropVariety.name.like(f'%{search_name}%'))
    if search_type:
        query = query.filter(CropVariety.crop_type.like(f'%{search_type}%'))

    pagination = query.order_by(CropVariety.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
        
    return render_template('data/crop_list.html', 
                         pagination=pagination,
                         search_name=search_name,
                         search_type=search_type)

@bp.route('/crop/add', methods=['GET', 'POST'])
@login_required
def crop_add():
    if request.method == 'POST':
        try:
            variety = CropVariety(
                name=request.form['name'],
                crop_type=request.form['crop_type'],
                characteristics=request.form['characteristics'],
                yield_potential=request.form['yield_potential'],
                market_value=request.form['market_value']
            )
            db.session.add(variety)
            db.session.commit()
            flash('作物品种添加成功', 'success')
            return redirect(url_for('data.crop_list'))
        except Exception as e:
            flash('数据添加失败', 'danger')
    return render_template('data/crop_form.html')

@bp.route('/crop/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def crop_edit(id):
    data = CropVariety.query.get_or_404(id)
    
    if request.method == 'POST':
        try:
            data.name = request.form['name']
            data.crop_type = request.form['crop_type']
            data.characteristics = request.form['characteristics']
            data.yield_potential = request.form['yield_potential']
            data.market_value = request.form['market_value']
            
            db.session.commit()
            flash('作物品种更新成功', 'success')
            return redirect(url_for('data.crop_list'))
        except Exception as e:
            flash('数据更新失败', 'danger')
            
    return render_template('data/crop_edit.html', data=data)

@bp.route('/crop/<int:id>/delete', methods=['POST'])
@login_required
def crop_delete(id):
    data = CropVariety.query.get_or_404(id)
    try:
        db.session.delete(data)
        db.session.commit()
        flash('作物品种删除成功', 'success')
    except Exception as e:
        flash('删除失败', 'danger')
    return redirect(url_for('data.crop_list'))

# 环境数据路由
@bp.route('/environment')
@login_required
def environment_list():
    page = request.args.get('page', 1, type=int)
    search_region = request.args.get('search_region', '')
    date_from = request.args.get('date_from', '')
    date_to = request.args.get('date_to', '')

    query = EnvironmentData.query

    if search_region:
        query = query.filter(EnvironmentData.region.like(f'%{search_region}%'))
    if date_from:
        query = query.filter(EnvironmentData.date >= datetime.strptime(date_from, '%Y-%m-%d'))
    if date_to:
        query = query.filter(EnvironmentData.date <= datetime.strptime(date_to, '%Y-%m-%d'))

    pagination = query.order_by(EnvironmentData.date.desc()).paginate(
        page=page, per_page=10, error_out=False)
        
    return render_template('data/environment_list.html', 
                         pagination=pagination,
                         search_region=search_region,
                         date_from=date_from,
                         date_to=date_to)

@bp.route('/environment/add', methods=['GET', 'POST'])
@login_required
def environment_add():
    if request.method == 'POST':
        try:
            data = EnvironmentData(
                region=request.form['region'],
                date=datetime.strptime(request.form['date'], '%Y-%m-%d'),
                temperature=float(request.form['temperature']),
                rainfall=float(request.form['rainfall']),
                soil_type=request.form['soil_type'],
                soil_fertility=request.form['soil_fertility'],
                light_intensity=float(request.form['light_intensity'])
            )
            db.session.add(data)
            db.session.commit()
            flash('环境数据添加成功', 'success')
            return redirect(url_for('data.environment_list'))
        except Exception as e:
            flash('数据添加失败', 'danger')
    return render_template('data/environment_form.html')

@bp.route('/environment/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def environment_edit(id):
    data = EnvironmentData.query.get_or_404(id)
    
    if request.method == 'POST':
        try:
            data.region = request.form['region']
            data.date = datetime.strptime(request.form['date'], '%Y-%m-%d')
            data.temperature = float(request.form['temperature'])
            data.rainfall = float(request.form['rainfall'])
            data.soil_type = request.form['soil_type']
            data.soil_fertility = request.form['soil_fertility']
            data.light_intensity = float(request.form['light_intensity'])
            
            db.session.commit()
            flash('环境数据更新成功', 'success')
            return redirect(url_for('data.environment_list'))
        except Exception as e:
            flash('数据更新失败', 'danger')
            
    return render_template('data/environment_edit.html', data=data)

@bp.route('/environment/<int:id>/delete', methods=['POST'])
@login_required
def environment_delete(id):
    data = EnvironmentData.query.get_or_404(id)
    try:
        db.session.delete(data)
        db.session.commit()
        flash('环境数据删除成功', 'success')
    except Exception as e:
        flash('删除失败', 'danger')
    return redirect(url_for('data.environment_list')) 